import psutil
import platform
import demjson


def get_cpu_info():
    """
    :return: 系统cpu信息
    """
    cpu = {"times": psutil.cpu_times(),
           "percent": psutil.cpu_percent(),
           "count": psutil.cpu_count(False),
           "logic_count": psutil.cpu_count(True),
           "stats": psutil.cpu_stats(),
           "freq": psutil.cpu_freq()}
    return cpu


def get_memory_info():
    """
    :return: 系统内存信息
    """
    memory = {"physical": psutil.virtual_memory(),
              "swap": psutil.swap_memory()}
    return memory


def get_disks_info():
    """
    :return: 系统硬盘信息
    """
    disks_info = {}
    for disk in psutil.disk_partitions():
        """:type psutil._common.sdiskpart"""
        disks_info[disk.device] = {}
        disks_info[disk.device]["partition"] = disk
        disks_info[disk.device]["usage"] = psutil.disk_usage(disk.mountpoint)
    return disks_info


def get_net_info():
    """
    :return: 系统网络信息
    """
    net_info = {"all": psutil.net_io_counters()}
    nic_counter = psutil.net_io_counters(True)
    nic_addr = psutil.net_if_addrs()
    nic_stats = psutil.net_if_stats()
    nic_list = nic_counter.keys()
    for nic in nic_list:
        net_info[nic] = {}
        net_info[nic]["io_counter"] = nic_counter[nic]
        # 转换addr中的family值
        net_info[nic]["addr"] = nic_addr[nic]
        for i in range(len(net_info[nic]["addr"])):
            addr_info = net_info[nic]["addr"][i]
            family = addr_info.family.name
            temp = demjson.decode(demjson.encode(addr_info).replace("AddressFamily." + family, "\"" + family + "\""))
            net_info[nic]["addr"][i] = temp
        # 转换stats中的duplex值
        net_info[nic]["stat"] = nic_stats[nic]
        duplex = nic_stats[nic].duplex.name
        net_info[nic]["stat"] = demjson.decode(demjson.encode(nic_stats[nic])
                                               .replace("NicDuplex." + duplex, "\"" + duplex + "\""))
    return net_info


def get_system_utilization():
    """
    :return: 系统资源利用情况
    """
    system_utilization = {"cpu": get_cpu_info(),
                          "memory": get_memory_info(),
                          "disks": get_disks_info(),
                          "net": get_net_info()
                          }
    return system_utilization


def get_system_info():
    """
    :return: 系统信息
    """
    system_info = {"platform_name": platform.platform(),
                   "version": platform.version(),
                   "architecture": platform.architecture(),
                   "machine":platform.machine(),
                   "node":platform.node(),
                   "processor":platform.processor()
                   }
    return system_info


def main():
    json = {"system_utilization": get_system_utilization(),
            "system_info": get_system_info()}
    return demjson.encode(json)


if __name__ == '__main__':
    print(main())
    print(demjson.decode(main()))
